<template>
  <div class="line-chart-wrapper">
    <div ref="lineChart" class="chart-container"></div>
    <div v-if="loading" class="chart-loading">
      <el-icon class="is-loading"><Loading /></el-icon>
      <span>加载中...</span>
    </div>
    <div v-if="!loading && isEmpty" class="chart-empty">
      <el-empty description="暂无数据" />
    </div>
  </div>
</template>

<script setup>
import {nextTick, onMounted, onUnmounted, ref, watch} from 'vue'
import * as echarts from 'echarts'
import {Loading} from '@element-plus/icons-vue'
import {postList} from "@/uses/handleData.js";

const props = defineProps({
  // 图表标题
  title: {
    type: String,
    default: ''
  },
  // 数据模型
  model: {
    type: String,
    required: false
  },
  // 静态数据（当不使用 model 时）
  data: {
    type: Object,
    default: () => ({
      xAxis: [],
      series: []
    })
  },
  // X轴数据字段
  xAxisKey: {
    type: String,
    default: 'name'
  },
  // Y轴数据字段（可以是数组，支持多条线）
  yAxisKeys: {
    type: Array,
    default: () => ['value']
  },
  // 系列名称（与 yAxisKeys 对应）
  seriesNames: {
    type: Array,
    default: () => []
  },
  // 图表高度
  height: {
    type: String,
    default: '350px'
  },
  // 是否平滑曲线
  smooth: {
    type: Boolean,
    default: true
  },
  // 是否显示区域填充
  showArea: {
    type: Boolean,
    default: false
  },
  // 是否显示数据点
  showSymbol: {
    type: Boolean,
    default: true
  },
  // 是否显示图例
  showLegend: {
    type: Boolean,
    default: true
  },
  // 图例位置
  legendPosition: {
    type: String,
    default: 'top', // top, bottom
    validator: (value) => ['top', 'bottom'].includes(value)
  },
  // 是否显示网格线
  showGrid: {
    type: Boolean,
    default: true
  },
  // 自定义颜色
  colors: {
    type: Array,
    default: () => [
      '#5470c6',
      '#91cc75',
      '#fac858',
      '#ee6666',
      '#73c0de',
      '#3ba272',
      '#fc8452',
      '#9a60b4',
      '#ea7ccc'
    ]
  },
  // 动画效果
  animation: {
    type: Boolean,
    default: true
  },
  // Y轴名称
  yAxisName: {
    type: String,
    default: ''
  },
  // X轴名称
  xAxisName: {
    type: String,
    default: ''
  },
  // 是否显示缩放工具
  showDataZoom: {
    type: Boolean,
    default: false
  }
})

const lineChart = ref(null)
let chartInstance = null
const loading = ref(false)
const isEmpty = ref(false)

// 获取图例配置
const getLegendConfig = () => {
  if (!props.showLegend) {
    return { show: false }
  }

  const positions = {
    top: { top: '10', left: 'center' },
    bottom: { bottom: '10', left: 'center' }
  }

  return {
    orient: 'horizontal',
    type: 'scroll',
    textStyle: {
      fontSize: 12,
      color: '#666'
    },
    pageTextStyle: {
      color: '#999'
    },
    ...positions[props.legendPosition]
  }
}

// 初始化图表配置
const getOption = (xAxisData, seriesData) => {
  const option = {
    color: props.colors,
    title: props.title ? {
      text: props.title,
      left: 'center',
      top: props.legendPosition === 'top' ? '40' : '10',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#333'
      }
    } : null,
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(50, 50, 50, 0.9)',
      borderColor: '#333',
      borderWidth: 1,
      textStyle: {
        color: '#fff'
      },
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      }
    },
    legend: getLegendConfig(),
    grid: {
      left: '3%',
      right: '4%',
      bottom: props.showDataZoom ? '15%' : '10%',
      top: props.title ? (props.legendPosition === 'top' ? '80' : '60') : (props.legendPosition === 'top' ? '50' : '40'),
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: xAxisData,
      name: props.xAxisName,
      nameTextStyle: {
        color: '#666',
        fontSize: 12
      },
      axisLine: {
        lineStyle: {
          color: '#ddd'
        }
      },
      axisLabel: {
        color: '#666',
        fontSize: 11
      },
      splitLine: {
        show: props.showGrid,
        lineStyle: {
          color: '#f0f0f0',
          type: 'dashed'
        }
      }
    },
    yAxis: {
      type: 'value',
      name: props.yAxisName,
      nameTextStyle: {
        color: '#666',
        fontSize: 12
      },
      axisLine: {
        show: false
      },
      axisLabel: {
        color: '#666',
        fontSize: 11
      },
      splitLine: {
        show: props.showGrid,
        lineStyle: {
          color: '#f0f0f0',
          type: 'dashed'
        }
      }
    },
    series: seriesData,
    animation: props.animation
  }

  // 添加数据缩放
  if (props.showDataZoom) {
    option.dataZoom = [
      {
        type: 'slider',
        show: true,
        start: 0,
        end: 100,
        height: 20,
        bottom: '5%'
      },
      {
        type: 'inside',
        start: 0,
        end: 100
      }
    ]
  }

  return option
}

// 初始化图表
const initChart = (xAxisData, seriesData) => {
  if (!lineChart.value) return

  // 如果实例已存在，先销毁
  if (chartInstance) {
    chartInstance.dispose()
  }

  chartInstance = echarts.init(lineChart.value)
  chartInstance.setOption(getOption(xAxisData, seriesData))

  // 添加窗口大小改变监听
  window.addEventListener('resize', handleResize)
}

// 处理窗口大小改变
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

// 加载数据
const loadData = async () => {
  try {
    loading.value = true
    isEmpty.value = false

    let xAxisData = []
    let seriesData = []

    // 如果有静态数据，使用静态数据
    if (props.data && (props.data.xAxis?.length > 0 || props.data.series?.length > 0)) {
      xAxisData = props.data.xAxis || []
      seriesData = props.data.series || []
    }
    // 否则从 API 加载
    else if (props.model) {
      let res = await postList(props.model, {})
      if (res.code === 200 && res.data && res.data.length > 0) {
        // 提取 X 轴数据
        xAxisData = res.data.map(item => item[props.xAxisKey])
        
        // 为每个 Y 轴字段创建系列
        seriesData = props.yAxisKeys.map((key, index) => {
          const seriesName = props.seriesNames[index] || key
          const data = res.data.map(item => item[key])
          
          return {
            name: seriesName,
            type: 'line',
            smooth: props.smooth,
            showSymbol: props.showSymbol,
            symbolSize: 6,
            data: data,
            areaStyle: props.showArea ? {
              opacity: 0.3
            } : null,
            lineStyle: {
              width: 2
            },
            emphasis: {
              focus: 'series',
              itemStyle: {
                shadowBlur: 10,
                shadowColor: 'rgba(0, 0, 0, 0.3)'
              }
            }
          }
        })
        
        console.info('折线图数据:', { xAxisData, seriesData })
      }
    }

    // 检查是否有数据
    if (xAxisData.length === 0 || seriesData.length === 0) {
      isEmpty.value = true
      return
    }

    await nextTick()
    initChart(xAxisData, seriesData)
  } catch (error) {
    console.error('加载折线图数据失败:', error)
    isEmpty.value = true
  } finally {
    loading.value = false
  }
}

// 监听数据变化
watch(() => props.data, () => {
  if (props.data && (props.data.xAxis?.length > 0 || props.data.series?.length > 0)) {
    loadData()
  }
}, { deep: true })

// 监听配置变化
watch(() => [props.colors, props.smooth, props.showArea, props.showSymbol, props.showLegend, props.legendPosition, props.showGrid], () => {
  if (chartInstance) {
    loadData()
  }
}, { deep: true })

onMounted(() => {
  loadData()
})

onUnmounted(() => {
  if (chartInstance) {
    window.removeEventListener('resize', handleResize)
    chartInstance.dispose()
    chartInstance = null
  }
})

// 暴露刷新方法
defineExpose({
  refresh: loadData,
  getInstance: () => chartInstance
})
</script>

<style scoped lang="scss">
.line-chart-wrapper {
  position: relative;
  width: 100%;
  height: v-bind(height);

  .chart-container {
    width: 100%;
    height: 100%;
  }

  .chart-loading {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;
    color: #999;
    font-size: 14px;

    .el-icon {
      font-size: 32px;
    }
  }

  .chart-empty {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 100%;
  }
}
</style>

